/**
 * 
 */
package com.thon.task.system;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import com.google.common.collect.Maps;
import com.thon.commons.config.Global;
import com.thon.entity.project.Project;
import com.thon.entity.project.ProjectAttention;
import com.thon.entity.project.ProjectCategory;
import com.thon.entity.project.ProjectRecommend;
import com.thon.entity.project.ProjectSupport;
import com.thon.entity.user.Coupon;
import com.thon.entity.user.User;
import com.thon.service.message.TextMessageService;
import com.thon.service.project.ProjectCategoryService;
import com.thon.service.project.ProjectRecommendService;
import com.thon.service.project.ProjectService;
import com.thon.service.project.ProjectSupportService;
import com.thon.service.system.AuthService;
import com.thon.service.user.CouponService;
import com.thon.service.user.MessageService;
import com.thon.service.user.UserService;
import com.thon.service.user.UserSettingService;
import com.thon.task.Task;

/**
 * @author THON
 * @email thon.ju@meet-future.com
 * @date 2011-11-27 下午04:36:02
 * @description:
 */
@Aspect
@Component
public class SystemAspect {
	
	@Autowired
	private Task registEmailTask;
	@Autowired
	private Task forgetEmailTask;
	@Autowired
	private UserService userService;
	@Autowired
	private UserSettingService userSettingService;
	@Autowired
	private ProjectService projectService;
	@Autowired
	private MessageService messageService;
	@Autowired
	private ProjectRecommendService projectRecommendService;
	@Autowired
	private ProjectCategoryService projectCategoryService;
	@Autowired
	private ProjectSupportService projectSupportService;
	@Autowired
	private TextMessageService textMessageService;
	@Autowired
	private CouponService couponService;
	@Autowired
	private AuthService authService;
	
	/**
	 * 激活用户
	 * @param jp
	 */
	@AfterReturning("execution(*  com.thon.service.user.UserService.registUser(..))")
	public void doUpdateBookingStatus(JoinPoint jp) {
//		Map<Object, Object> context =new HashMap<Object, Object>();
		User user = (User)jp.getArgs()[0];
		//context.put("user", user);		
		//registEmailTask.doAsyncTask(context);
		User oldUser = userService.getUser(user.getId());
		oldUser.setStatus("open");
	}
	
//	/**
//	 * 忘记密码
//	 * @param jp
//	 */
//	@AfterReturning("execution(*  com.thon.service.user.UserService.sendMail2User(..))")
//	public void doForgetPassword(JoinPoint jp) {
//		Map<Object, Object> context =new HashMap<Object, Object>();
//		User user = (User)jp.getArgs()[0];
//		context.put("user", user);
//		forgetEmailTask.doAsyncTask(context);
//	}
	
	@AfterReturning("execution(*  com.thon.service.project.ProjectRecommendService.add(..))")
	public void updateProjectStatus(JoinPoint jp) {
		ProjectRecommend projectRecommend = (ProjectRecommend)jp.getArgs()[0];
		Project project = projectService.getProject(projectRecommend.getUser().getId(), projectRecommend.getProject().getId());
		int recommendCount= projectRecommendService.countProjectRecommend(project.getId()).intValue();
		if(recommendCount == 2){
			project.setStatus(3);
			project.setFundraisingDate(new Date());
			projectService.updateProject(project);
			Long amount = projectService.countProject("category_id", project.getProjectCategory().getId());
			ProjectCategory projectCategory = projectCategoryService.getProjectCategory(project.getProjectCategory().getId());
			//项目推荐数量+1，如果其他接口也调用了ProjectRecommendService.add(..)，那么产生的错误应该就是这里
			//projectCategory.setProjectAmount(++amount);
			projectCategoryService.updateProjectCategory(projectCategory);
		}
	}
	
	//更新项目分类的统计	
	@AfterReturning("execution(*  com.thon.service.project.ProjectService.addProject(..))")
	public void countAddAmountCategory(JoinPoint jp) {				
				Map<Integer,Integer> newCategoryAmount = projectCategoryService.getAmount();		
				newCategoryAmount=projectService.countCategoryAmount(newCategoryAmount);
				projectCategoryService.updateAmount(newCategoryAmount);
	}
	
	//更新项目分类的统计	
	@AfterReturning("execution(*  com.thon.service.project.ProjectService.updateProject(..))")
	public void countUpdateAmountCategory(JoinPoint jp) {				
				Map<Integer,Integer> newCategoryAmount = projectCategoryService.getAmount();		
				newCategoryAmount=projectService.countCategoryAmount(newCategoryAmount);
				projectCategoryService.updateAmount(newCategoryAmount);
	}
	
	@AfterReturning("execution(*  com.thon.service.project.ProjectAttentionService.add(..))")
	public void sendAttentionMessage(JoinPoint jp) {
		ProjectAttention projectAttention = (ProjectAttention)jp.getArgs()[0];
		User from = new User();
		from = userService.getUserByEmail(Global.getConfig("service.user"));
		User to = projectService.getProject(projectAttention.getProject().getId()).getInstitution().getUser();//.getInstitution().getUser();
		Project project = projectService.getProject(projectAttention.getProject().getId());
		if (userSettingService.SettingStatus(to.getId(), "supportMe")) {
			User user = userService.getUser(projectAttention.getUserId());
			messageService.sendMessage(from, to, "亲爱的:"+to.getName()+"，"+user.getName()+"关注了您的活动：《"+project.getName()+"》。");
		}
	}
	
	@AfterReturning("execution(*  com.thon.service.user.PresentService.sendMail(..))")
	public void sendPresentTextAndMessage(JoinPoint jp) throws IOException {
		ProjectSupport ps = (ProjectSupport)jp.getArgs()[0];
		User user = (User)jp.getArgs()[1];
		User newUser = (User)jp.getArgs()[2];
		ps = projectSupportService.getProjectSupport(ps.getId());
//		Project projectSupport = project
		User from = userService.getUserByEmail(Global.getConfig("service.user"));
		User to = userService.getUser(user.getId());
		String text = "亲爱的"+to.getName()+"，"+newUser.getName()+"向您赠送了"+ps.getProduct().getName();
		messageService.sendMessage(from, to, text);
		String value =  "#user1#="+newUser.getName()+"&"+"#user2#="+to.getName()+"&"+"#goods#="+ps.getProduct().getName();
		
		//String text2 = String.valueOf(Math.random()).substring(2,8);
		//String value = "#code#="+text2;
		//String loginName = user.getLoginName();
		//textMessageService.tplSendSms(value, loginName, TextMessageService.SEND_VERIFICATION_CODE);
		textMessageService.tplSendSms(value, to.getLoginName(), TextMessageService.SEND_PRESENT_MESSAGE);
	}
	
	@AfterReturning("execution(*  com.thon.service.user.PresentService.addUser(..))")
	public void sendHelpRegistTextAndMessage(JoinPoint jp) throws IOException {
		User user = (User)jp.getArgs()[0];
		user = userService.getUser(user.getId());
		//ProjectSupport ps = (ProjectSupport)jp.getArgs()[1];
		//ps = projectSupportService.getProjectSupport(ps.getId());
		//String value = "#user1#="+ps.getUserName()+"#user2#="+user.getName()+"#code#="+user.getPlainPassword();
		String value = "#user#=+"+user.getLoginName()+"&"+"#msg#="+user.getPlainPassword();
		textMessageService.tplSendSms(value, user.getLoginName(), TextMessageService.SEND_AUTO_REGIST_MESSAGE);
	}
	
	@AfterReturning("execution(*  com.thon.service.user.CouponService.sendText(..))")
	public void sendActivityCouponMessage(JoinPoint jp) throws IOException {
		Coupon c = (Coupon)jp.getArgs()[0];
		Coupon coupon = couponService.getCouponById(c.getId());
		String value = "#user#="+coupon.getUser().getName()+"#msg#="+coupon.getMemo()+","+coupon.getCouponNo();
		textMessageService.tplSendSms(value, coupon.getUser().getLoginName(), TextMessageService.SEND_REMIND_MESSAGE);
	}
	
	/**
	 * 激活用户
	 * @param jp
	 */
	@AfterReturning("execution(*  com.thon.service.system.AuthService.save(..))")
	public void doUpdateFilterChain(JoinPoint jp) {
		authService.reCreateFilterChains();
	}
}
